package main

import (
	"context"
	"flag"
	"net"
	"net/http"

	"github.com/golang/glog"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	gw "gateway_demo/gen/go/your/service/v1" // Update
)

var (
	// command-line options:
	// gRPC server endpoint
	grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:9090", "gRPC server endpoint")
)

type MyServer struct {
}

const (
	HTTPLISTEN = ":8081"
	GRPCLISTEN = ":9091"
)

func (me *MyServer) Echo(c context.Context, req *gw.StringMessage) (*gw.StringMessage, error) {
	return &gw.StringMessage{Value: "ssss+" + req.Value}, nil
}
func (me *MyServer) mustEmbedUnimplementedYourServiceServer() {}

func run() error {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	// Register gRPC server endpoint

	lis, err := net.Listen("tcp", GRPCLISTEN)
	if err != nil {
		panic(err.Error())
	}
	grpcServer := grpc.NewServer()
	var myServer = MyServer{}
	gw.RegisterYourServiceServer(grpcServer, &myServer)
	go grpcServer.Serve(lis)

	// Note: Make sure the gRPC server is running properly and accessible
	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
	err = gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, GRPCLISTEN, opts)
	// err = gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, ":9091", opts)

	if err != nil {
		return err
	}

	// Start HTTP server (and proxy calls to gRPC server endpoint)
	return http.ListenAndServe(HTTPLISTEN, mux)
}

func main() {
	flag.Parse()
	defer glog.Flush()

	if err := run(); err != nil {
		glog.Fatal(err)
	}
}
